//
//  ShareSDK.swift
//  ShareSDK_Swift
//
//  Created by ZhiPeng Ben on 15/7/2.
//  Copyright (c) 2015年 ZhiPeng Ben. All rights reserved.
//

import Foundation
import MessageUI


public typealias ShareFinished = (status: Bool) -> ()
private let instance = ShareSDK()
public class ShareSDK:NSObject{
    
    public var shareFinsihed:ShareFinished?
    
    /// 分享的单例
    public class var sharedManager: ShareSDK {
        return instance
    }
    
    /**
    注册微信
    
    :param: appid 微信开发者ID
    */
    public func registAppForWX(appid:String) {
        WXApi.registerApp(appid)
    }
    
    /**
    注册QQ
    
    :param: appid QQ开发者的ID
    */
    public func registAppForQQ(appid:String) {
        WeiboSDK.registerApp(appid)
    }
    
    /**
    获取根视图
    
    :returns: 返回根视图
    */
    public func  rootViewController() -> UIViewController? {
        return UIApplication.sharedApplication().keyWindow?.rootViewController
    }
}

// MARK: - Mail
extension ShareSDK:MFMailComposeViewControllerDelegate {
    
    
    public func mailShareApp(title:String, body:String, attach:String) {
        let mailComposerVC = MFMailComposeViewController()
        if MFMailComposeViewController.canSendMail() {
            mailComposerVC.mailComposeDelegate = self
            mailComposerVC.setSubject(title)
            mailComposerVC.setMessageBody(body, isHTML: false)
            var mineType = "image/png"
            mailComposerVC.addAttachmentData(NSData(contentsOfFile: attach), mimeType: mineType, fileName: attach.lastPathComponent)
            self.rootViewController()?.presentViewController(mailComposerVC, animated: true, completion: nil)
        } else {

            var alertView = UIAlertView(title:nil, message: "设备不支持邮件功能", delegate: nil, cancelButtonTitle: "确定")
            alertView.show()
            
        }
    }
    
    public func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
     
        var status = false as Bool
        if  result.value == MFMailComposeResultSent.value {
            status = true
        }
        
        if  self.shareFinsihed != nil{
            self.shareFinsihed!(status: status)
        }
    }
    
    
}

// MARK: - SMS
extension ShareSDK:MFMessageComposeViewControllerDelegate {
    
    public func smsShareApp(title:String, body:String, attach:String) {
        let smsComposerVC = MFMessageComposeViewController()
        if MFMessageComposeViewController.canSendText() {
            smsComposerVC.messageComposeDelegate = self
            smsComposerVC.body = body
            smsComposerVC.title = title
            smsComposerVC.addAttachmentURL(NSURL(fileURLWithPath: attach), withAlternateFilename: nil)
            self.rootViewController()?.presentViewController(smsComposerVC, animated: true, completion: nil)
        } else {
            
            var alertView = UIAlertView(title:nil, message: "设备不支持短信功能", delegate: nil, cancelButtonTitle: "确定")
            alertView.show()
            
        }
    }
    
    public func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
        
        var status = false as Bool
        if  result.value == MessageComposeResultSent.value {
            status = true
        }
        
        if  self.shareFinsihed != nil{
            self.shareFinsihed!(status: status)
        }
    }
}



// MARK: - WeiXin
extension ShareSDK:WXApiDelegate {
   
    public func weixinShareApp(title:String,des:String,image:UIImage,url:String,scence:WXScene) {
        
        var message:WXMediaMessage = WXMediaMessage()
        message.title = title;
        message.description = des;
        message.setThumbImage(image)
        var ext:WXAppExtendObject = WXAppExtendObject()
        ext.url = url;
        
        
        message.mediaObject = ext;
        var req:SendMessageToWXReq = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scence.value)
        WXApi.sendReq(req)
        
    }
    
    public func  weiXinHandleOpenURL(url:NSURL) {
        WXApi.handleOpenURL(url, delegate: self)
    }
    
    public func  weiXinCheckIsInstalled() -> Bool {
        return  WXApi.isWXAppSupportApi() && WXApi.isWXAppInstalled()
    }

    
    public func onReq(req: BaseReq!) {
        
    }
    
    public func onResp(resp: BaseResp!) {
        
        if  resp.isKindOfClass(SendMessageToQQResp) {
            var status = false as Bool
            if  resp.errCode == WXSuccess.value {
                status = true
            }
            if  self.shareFinsihed != nil{
                self.shareFinsihed!(status: status)
            }
        }else if resp.isKindOfClass(SendAuthResp) {
            
        }else if resp.isKindOfClass(AddCardToWXCardPackageResp){
            
        }else {
            
        }
    }
   
}


let  errorMessages = [
    "App未注册",
    "发送参数错误",
    "未安装手Q",
    "API接口不支持",
    "发送失败",
    "空间分享不支持纯文本分享，请使用图文分享",
    "空间分享不支持纯图片分享，请使用图文分享"
]
// MARK: - QQ
extension ShareSDK {
   
    public func qqShareApp(title:String,des:String,image:UIImage,url:String,isQzone:Bool) {
        
        var  newsObj = QQApiNewsObject.objectWithURL(NSURL(string: url)!, title: title, description: des, previewImageData: UIImageJPEGRepresentation(image, 1)) as! QQApiNewsObject
        var req = SendMessageToQQReq(content: newsObj)
        var sent:QQApiSendResultCode
        if isQzone {
            sent = QQApiInterface.SendReqToQZone(req)
        }else {
            sent = QQApiInterface.sendReq(req)
        }
    }
    
    private func handleSendResult(sendResult:QQApiSendResultCode) {
        
        var status:Bool = false
        switch (sendResult.value) {
            case EQQAPIAPPNOTREGISTED.value:
                quickAlertViewWithMessage(errorMessages[0])
                break
            case EQQAPIMESSAGECONTENTINVALID.value:
                break
            case EQQAPIMESSAGECONTENTNULL.value:
                break
            case EQQAPIMESSAGETYPEINVALID.value:
                quickAlertViewWithMessage(errorMessages[1])
                break;
            case EQQAPIQQNOTINSTALLED.value:
                quickAlertViewWithMessage(errorMessages[2])
                break
            case EQQAPIQQNOTSUPPORTAPI.value:
                quickAlertViewWithMessage(errorMessages[3])
                break;
            case EQQAPISENDFAILD.value:
                quickAlertViewWithMessage(errorMessages[4])
                break;
            case EQQAPIQZONENOTSUPPORTTEXT.value:
                quickAlertViewWithMessage(errorMessages[5])
                break
            case EQQAPIQZONENOTSUPPORTIMAGE.value:
                quickAlertViewWithMessage(errorMessages[6])
                break;
            case EQQAPISENDSUCESS.value:
                status = true;
                break;
            default:
                break
        }
        if  self.shareFinsihed != nil{
            self.shareFinsihed!(status: status)
        }
    }
    
    
    public func qqCheckIsInstalled() -> Bool{
        
        return TencentOAuth.iphoneQQInstalled() && TencentOAuth.iphoneQQSupportSSOLogin()
    }
    
    
    public func qqHandleOpenURL(url:NSURL) {
        TencentOAuth.HandleOpenURL(url)
    }
    
    private func quickAlertViewWithMessage(message:String) {
        
        var alertView = UIAlertView(title:"Error", message: message, delegate: nil, cancelButtonTitle: "取消")
        alertView.show()
    }
}

// MARK: - WeiBo
extension ShareSDK:WeiboSDKDelegate {
    
    public func weiboShareApp(title:String,des:String,image:UIImage,url:String) {
        
        var message = WBMessageObject()
        var webpage = WBWebpageObject()
        webpage.title = title
        webpage.objectID = "\(NSDate().timeIntervalSince1970)"
        webpage.description = des + "\(NSDate().timeIntervalSince1970)"
        webpage.thumbnailData = UIImageJPEGRepresentation(image, 1)
        webpage.webpageUrl = url
        message.mediaObject = webpage
        
        var authRequest = WBAuthorizeRequest()
        authRequest.redirectURI = "http://www.baidu.com";
        authRequest.scope = "all";
        
        var request = WBSendMessageToWeiboRequest.requestWithMessage(message, authInfo: authRequest, access_token: nil) as! WBSendMessageToWeiboRequest
        WeiboSDK.sendRequest(request)
    }

    
    public func weiBoCheckIsInstalled() -> Bool{
        return WeiboSDK.isWeiboAppInstalled() && WeiboSDK.isCanShareInWeiboAPP()
    }
    
    public func weiBoHandleOpenURL(url:NSURL) {
        WeiboSDK.handleOpenURL(url, delegate: self)
    }

    
    public func didReceiveWeiboRequest(request: WBBaseRequest!) {
        
    }
    
    public func didReceiveWeiboResponse(response: WBBaseResponse!) {
        
        if response.isKindOfClass(WBSendMessageToWeiboResponse){
            
            var status:Bool = false
            if response.statusCode == WeiboSDKResponseStatusCode.Success {
                status = true
            }
            if  self.shareFinsihed != nil{
                self.shareFinsihed!(status: status)
            }
        }else if response.isKindOfClass(WBAuthorizeResponse){
            
            
        }else if response.isKindOfClass(WBPaymentResponse){
            
            
        }else {
            
        }
    }
}